import React, { useState, useImperativeHandle, useEffect } from "react"
import { Popup } from "antd-mobile"
import { getListApi } from "@/apis"
import "./index.less"
import classNames from "classnames"

const PopupType = (props, ref) => {
  const onSelect = props.onSelect
  const [show, setShow] = useState(false) // 组件的显示和隐藏
  const [active, setActive] = useState("all") // 激活的 type
  const [expense, setExpense] = useState([]) // 支出类型标签
  const [income, setIncome] = useState([]) // 收入类型标签

  useEffect(() => {
    async function getList() {
      const { data } = await getListApi()
      const list = data.data.list
      setExpense(list.filter((i) => i.type === "1"))
      setIncome(list.filter((i) => i.type === "2"))
    }
    getList()
  }, [])

  const showP = () => {
    setShow(true)
  }
  const closeP = () => {
    setShow(false)
  }
  useImperativeHandle(ref, () => {
    return {
      showP,
      closeP,
    }
  })

  const choseType = (item) => {
    setActive(item.id)
    setShow(false)
    onSelect(item)
  }
  return (
    <div>
      <Popup
        visible={show}
        onMaskClick={() => {
          setShow(false)
        }}
        onClose={() => {
          setShow(false)
        }}
        ref={ref}
      >
        <div className="popupType">
          <div className="header">请选择类型</div>
          <div className="content">
            <div
              className={classNames("all", { active: active === "all" })}
              onClick={() => choseType({ id: "all" })}
            >
              全部类型
            </div>
            <div className="title">支出</div>
            <div className="expenseWrap">
              {expense.map((item, index) => (
                <div
                  key={index}
                  onClick={() => choseType(item)}
                  className={active === item.id ? "active" : undefined}
                >
                  {item.name}
                </div>
              ))}
            </div>
            <div className="title">收入</div>
            <div className="expenseWrap">
              {income.map((item, index) => (
                <div
                  key={index}
                  onClick={() => choseType(item)}
                  className={active === item.id ? "active" : undefined}
                >
                  {item.name}
                </div>
              ))}
            </div>
          </div>
        </div>
      </Popup>
    </div>
  )
}

PopupType.displayName = "MyPopupType"

export default React.forwardRef(PopupType)
